import { NextFunction, Response } from 'express';
import { HttpException } from '@exceptions/http.exception';
import { ValidationError } from 'class-validator';
import { logger } from '@utils/logger';
import { ApiResponseBuilder } from '@utils/api-response-builder';
import { saveAuditLog } from '@utils/save-audit-log';
import { RequestWithId } from '@/interfaces';
import { HttpError } from 'routing-controllers';

export const ErrorMiddleware = async (error: HttpError | HttpException | Error, req: RequestWithId, res: Response, next: NextFunction) => {
  try {
    logger.error(`${error.stack}`);
    await saveAuditLog(req, res, error);
    // 处理 class-validator 错误（假设附加在 error 上）
    if ('errors' in error && Array.isArray((error as any).errors)) {
      const errors = (error as any).errors as ValidationError[];
      if (errors.length > 0 && errors[0].constraints) {
        const messages: string[] = Object.values(errors[0].constraints);
        const httpCode = (error as any).httpCode || 400;
        logger.error(`[${req.method}] ${req.path} Caught ValidationError >> StatusCode:: ${httpCode}, Message:: ${messages}`);
        return res.status(200).json(new ApiResponseBuilder(req, res).error(messages[0], httpCode));
      }
    }
    // 处理 HttpException（自定义异常）
    if (error instanceof HttpError) {
      const { status = 500, message = '服务器内部错误', code } = error as HttpException;
      console.log(error);
      logger.error(`[${req.method}] ${req.path} Caught HttpError >> StatusCode:: ${status}, Message:: ${message}`);
      return res.status(200).json(new ApiResponseBuilder(req, res).error(message, code));
    }
    // 默认处理通用 Error
    const message = error.message;
    const statusCode = (error as any).httpCode || 500;
    logger.error(`[${req.method}] ${req.path} Caught DefaultError >> StatusCode:: ${statusCode}, Message:: ${message}`);
    return res.status(200).json(new ApiResponseBuilder(req, res).error('服务器内部错误', statusCode));
  } catch (error) {
    next(error);
  }
};
